package com.bit.springblogdemo.common.interceptor;

import com.bit.springblogdemo.common.constant.Constant;
import com.bit.springblogdemo.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor { //拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader(Constant.USEN_TOKEN_HEADER_kEY); //获取token
         log.info("从header中获取token "+ userToken);
        if(userToken==null){
            //拦截
            response.setStatus(401);//401 用未登录   403 用户没有权限
            return false;
        }
        //校验token是否合法
        Claims claims =JwtUtils.parseToken(userToken);
        if(claims==null){
            //拦截
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
